package enterprise.manage.security.utils;

import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: zhenmingyue
 * Date: 2011-7-4 14:42:22
 * Desc:
 * For :
 */
public class SecurityUtils {
    /**
     * session中userId的名字
     */
    public static final String SESSION_USER_ID = "session_user_id";
    public static final String SESSION_USER_NAME = "session_user_name";
    public static final String SESSION_USER = "session_user";   
    /**
     * 以下两个常量参照spring security的配置
     */
    public static final String ANONYMOUS_USER_NAME = "anonymousUser";


    /**
     * 允许继承扩展的构造函数
     */
    protected SecurityUtils() {
    }

    /**
     * 判断是否是匿名用户
     *
     * @return 返回是否是匿名用户
     */
    public static boolean isAnonymousUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (authentication == null) || ANONYMOUS_USER_NAME.equals(authentication.getName());
    }

    /**
     * 获得用户ID
     *
     * @param session HttpSession
     * @return 当前用户的id
     */
    public static Long getUserId(HttpSession session) {
        Long userId = (Long) session.getAttribute(SESSION_USER_ID);
        if (userId == null) {
            return null;
        }
        return userId;
    }
}
